/**********************************************************************************
Copyright (C), by AppleCai
Project                      : Study Kernel driver
Description                  : User Application for cdev
History                      :
CPU and Compiler             : AM335x,GCC
GenDate                      : 2020-10-28
OwnerBy                      : Apple Cai
**********************************************************************************/
#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "stdlib.h"
#include "string.h"
#include "poll.h"
#include "sys/select.h"
#include "sys/time.h"
#include "linux/ioctl.h"
#include "applepaper_cmd.h"
int main(int argc, char *argv[])
{
	int fd;
	int ret = 0;
	char *filename;
	struct pollfd fds;
	fd_set readfds,writefds;
	struct timeval timeout;
	unsigned char data;

	if (argc != 2) {
		printf("Error Usage!\r\n");
		return -1;
	}

	filename = argv[1];
	fd = open(filename, O_RDWR | O_NONBLOCK);
	if (fd < 0) {
		printf("Can't open file %s\r\n", filename);
		return -1;
	}
	else
	{
		if(ioctl(fd, APPLEPAPER_CLEAR, 0)<0)
			printf("clear file %s failed!\r\n",filename);
	#if 0
		/* 构造结构体 */
		fds.fd = fd;
		fds.events = POLLIN;
			
		while (1) {
			ret = poll(&fds, 1, 500);
			switch (ret) {
				case 0: 	/* timeout */
					break;
				case -1:	/* error */
					printf("error");
					break;
				default:  
					ret = read(fd, &data, sizeof(data));
					if (ret < 0) {
						printf("read eror happen\r\n");
					} else {
						if (data)
							printf("value=%d\r\n", data);
					}
					break;
			}	
		}
	#endif
		while(1){
		FD_ZERO(&readfds);
		FD_ZERO(&writefds);
		FD_SET(fd, &readfds);
		FD_SET(fd, &writefds);
		/* initialize timer 1s */
		timeout.tv_sec = 5;
		timeout.tv_usec = 0;

			ret = select(fd + 1, &readfds,NULL, NULL, &timeout);
			switch (ret) {
				case 0: 	/* timeout */
					/* pass */
					printf("timeout\n");
					break;
				case -1:	/* error */
					printf("error");
					break;
				default:  /* read date */
					if(FD_ISSET(fd, &readfds)) {    //check fd is in this set 
						ret = read(fd, &data, sizeof(data));
						if (ret < 0) {
							printf("read eror happen\r\n");
						} else {
							if (data)
								printf("%c", data);
						}
					}
					else
					{
						//printf("w\n");
					}
					break;
			}	
		}
		
	}

	close(fd);
	return ret;
}
